#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "cJSON.h"

#define MAX_INPUT_SIZE 4096
#define MAX_MESSAGES 50
#define API_URL "https://api.deepseek.com/v1/chat/completions"

// 消息结构体
typedef struct {
    char *role;
    char *content;
} Message;

// 对话历史
typedef struct {
    Message messages[MAX_MESSAGES];
    int count;
} ChatHistory;

// 存储API响应的结构体
struct MemoryStruct {
    char *memory;
    size_t size;
};

// 回调函数：存储HTTP响应数据
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    struct MemoryStruct *mem = (struct MemoryStruct *)userp;
    
    char *ptr = realloc(mem->memory, mem->size + realsize + 1);
    if(!ptr) {
        fprintf(stderr, "内存不足!\n");
        return 0;
    }
    
    mem->memory = ptr;
    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;
    
    return realsize;
}

// 初始化聊天历史
void initChatHistory(ChatHistory *history) {
    history->count = 0;
    for (int i = 0; i < MAX_MESSAGES; i++) {
        history->messages[i].role = NULL;
        history->messages[i].content = NULL;
    }
}

// 添加消息到聊天历史
void addMessage(ChatHistory *history, const char *role, const char *content) {
    if (history->count >= MAX_MESSAGES) {
        // 如果达到最大消息数，移除最早的消息
        free(history->messages[0].role);
        free(history->messages[0].content);
        
        // 移动所有消息
        for (int i = 0; i < MAX_MESSAGES - 1; i++) {
            history->messages[i].role = history->messages[i + 1].role;
            history->messages[i].content = history->messages[i + 1].content;
        }
        history->count--;
    }
    
    // 添加新消息
    history->messages[history->count].role = strdup(role);
    history->messages[history->count].content = strdup(content);
    history->count++;
}

// 清理聊天历史
void cleanupChatHistory(ChatHistory *history) {
    for (int i = 0; i < history->count; i++) {
        free(history->messages[i].role);
        free(history->messages[i].content);
    }
    history->count = 0;
}

// 从环境变量获取API密钥
const char *getApiKey() {
    const char *api_key = getenv("DEEPSEEK_API_KEY");
    if (!api_key) {
        fprintf(stderr, "错误: 未设置DEEPSEEK_API_KEY环境变量\n");
        fprintf(stderr, "请使用以下命令设置API密钥:\n");
        fprintf(stderr, "  export DEEPSEEK_API_KEY=your-api-key-here\n");
        return NULL;
    }
    return api_key;
}

// 发送请求到DeepSeek API
char *sendRequest(const char *api_key, const char *model, ChatHistory *history) {
    CURL *curl;
    CURLcode res;
    char *response_content = NULL;
    
    // 构建JSON请求体
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "model", model);
    
    cJSON *messages = cJSON_AddArrayToObject(root, "messages");
    for (int i = 0; i < history->count; i++) {
        cJSON *msg = cJSON_CreateObject();
        cJSON_AddStringToObject(msg, "role", history->messages[i].role);
        cJSON_AddStringToObject(msg, "content", history->messages[i].content);
        cJSON_AddItemToArray(messages, msg);
    }
    
    char *json_payload = cJSON_PrintUnformatted(root);
    
    // 初始化libcurl
    curl = curl_easy_init();
    
    if(curl) {
        // 设置HTTP头部
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, "Accept: application/json");
        char auth_header[256];
        snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", api_key);
        headers = curl_slist_append(headers, auth_header);
        
        // 配置请求选项
        curl_easy_setopt(curl, CURLOPT_URL, API_URL);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_payload);
        
        // 设置响应处理
        struct MemoryStruct chunk;
        chunk.memory = malloc(1);
        chunk.size = 0;
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        
        // 执行请求
        res = curl_easy_perform(curl);
        
        // 错误处理
        if(res != CURLE_OK) {
            fprintf(stderr, "请求失败: %s\n", curl_easy_strerror(res));
        } else {
            // 解析JSON响应
            cJSON *response = cJSON_Parse(chunk.memory);
            if(response) {
                cJSON *error = cJSON_GetObjectItem(response, "error");
                if (error) {
                    cJSON *error_message = cJSON_GetObjectItem(error, "message");
                    if (cJSON_IsString(error_message)) {
                        fprintf(stderr, "API错误: %s\n", error_message->valuestring);
                    } else {
                        fprintf(stderr, "API返回未知错误\n");
                    }
                } else {
                    cJSON *choices = cJSON_GetObjectItem(response, "choices");
                    if(choices && cJSON_IsArray(choices)) {
                        cJSON *first_choice = cJSON_GetArrayItem(choices, 0);
                        cJSON *message = cJSON_GetObjectItem(first_choice, "message");
                        cJSON *content = cJSON_GetObjectItem(message, "content");
                        
                        if(cJSON_IsString(content)) {
                            response_content = strdup(content->valuestring);
                        }
                    }
                }
                cJSON_Delete(response);
            } else {
                fprintf(stderr, "JSON解析错误: %s\n", chunk.memory);
            }
        }
        
        // 清理资源
        free(chunk.memory);
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }
    
    // 释放内存
    cJSON_Delete(root);
    free(json_payload);
    
    return response_content;
}

// 打印欢迎信息
void printWelcomeMessage() {
    printf("\n");
    printf("=================================================\n");
    printf("      DeepSeek AI 聊天程序 - C语言版本\n");
    printf("=================================================\n");
    printf("输入您的问题与AI对话，输入'exit'或'quit'退出程序\n");
    printf("输入'clear'清除对话历史\n");
    printf("=================================================\n\n");
}

// 主函数：交互式对话循环
int main(void) {
    // 初始化libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    
    // 获取API密钥
    const char *api_key = getApiKey();
    if (!api_key) {
        return 1;
    }
    
    // 设置模型
    const char *model = "deepseek-chat";
    
    // 初始化聊天历史
    ChatHistory history;
    initChatHistory(&history);
    
    // 添加系统消息
    addMessage(&history, "system", "你是由DeepSeek AI开发的一个有用的AI助手。");
    
    // 打印欢迎信息
    printWelcomeMessage();
    
    // 交互式对话循环
    char input[MAX_INPUT_SIZE];
    while (1) {
        // 获取用户输入
        printf("\n用户: ");
        if (!fgets(input, MAX_INPUT_SIZE, stdin)) {
            break;
        }
        
        // 移除换行符
        input[strcspn(input, "\n")] = 0;
        
        // 检查退出命令
        if (strcmp(input, "exit") == 0 || strcmp(input, "quit") == 0) {
            printf("再见！\n");
            break;
        }
        
        // 检查清除历史命令
        if (strcmp(input, "clear") == 0) {
            cleanupChatHistory(&history);
            addMessage(&history, "system", "你是由DeepSeek AI开发的一个有用的AI助手。");
            printf("对话历史已清除\n");
            continue;
        }
        
        // 添加用户消息到历史
        addMessage(&history, "user", input);
        
        // 发送请求到API
        printf("正在思考...\n");
        char *ai_response = sendRequest(api_key, model, &history);
        
        if (ai_response) {
            // 打印AI回复
            printf("\nAI: %s\n", ai_response);
            
            // 添加AI回复到历史
            addMessage(&history, "assistant", ai_response);
            
            // 释放响应内存
            free(ai_response);
        } else {
            printf("\nAI: 抱歉，我无法生成回复。请检查API密钥和网络连接。\n");
        }
    }
    
    // 清理资源
    cleanupChatHistory(&history);
    curl_global_cleanup();
    
    return 0;
}